﻿using System;

namespace sametexts_u8
{
    using Dapper;
    using ExcelConfig.Config;
    using sametexts_u8.Data;
    using sametexts_u8.Dto;
    using System.Collections;
    using System.Collections.Generic;

    internal class U8DB : IDisposable
    {
        public static AppConfigFile Config = SQLRunnerInit.GetConfig();

        internal IRepo repo;
        internal IRepo repo_001;

        public U8DB()
        {
            var connectstring = Config.Text("u8_002_2025");
            connectstring = SecurityTool.DecryptByAES(connectstring);
            repo = new MssqlRepo(connectstring);
            var connectstring001 = Config.Text("u8_001_2022");
            connectstring001 = SecurityTool.DecryptByAES(connectstring001);
            repo_001 = new MssqlRepo(connectstring001);
        }
        public void Dispose()
        {
            repo.Dispose();
            repo_001.Dispose();
        }
        public void Run(string command)
        {
            repo.Open();

            using (var transaction = repo.Connection.BeginTransaction())
            {
                try
                {
                    repo.Connection.Execute(command, null, transaction);
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    // 发生异常时回滚事务
                    transaction.Rollback();
                    // 处理异常
                    Console.WriteLine(ex.Message);
                }
            }
        }

        public int TotalInventory()
        {
            repo.Open();
            var bag = repo.Connection.QueryFirstOrDefault<int>("select count(*) from inventory where dEDate is null;");
            return bag;
        }

        public IEnumerable<M> ReadInventoryList()
        {
            repo.Open();
            var bag = repo.Connection.Query<M>("select cInvCode,cInvStd from inventory where dEDate is null;");
            return bag;
        }
    }
}
